package com.wechat.server.mp.service;


import com.wechat.server.mp.common.dto.Vote;
import com.wechat.server.mp.common.exception.HasVoteException;
import com.wechat.server.mp.common.exception.VoteException;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.Valid;

/**
 * Created by andy on 2016/12/29.
 */
@Service
public class VoteService {


    @Autowired
    @Qualifier("redisTemplate0")
    private RedisTemplate zoeRedisTemplate0;
    @Autowired
    private WxMpServiceImpl wxMpService;

    public void save(@Valid Vote vote) throws HasVoteException, VoteException, WxErrorException {
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(vote.getId());
        Long add = zoeRedisTemplate0.opsForSet().add(vote.getJid(), wxMpUser.getOpenId());
        
        if (add == 0) {
            throw new HasVoteException();
        } else if (add != 1) {
            throw new VoteException();
        }
    }
}
